package com.web.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class WebServer implements Runnable {

    @Value("${netty.port}")
    private int port;//监听端口

    @Autowired
    ChannelInboundHandler channelInboundHandler;

    NioEventLoopGroup bossGroup;
    NioEventLoopGroup workGroup;
    private Thread thread;


    @PostConstruct
    public void init() {
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        workGroup = new NioEventLoopGroup();
        bossGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //获取到PipeLine
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(channelInboundHandler);
                        }
                    })
            .childOption(ChannelOption.SO_KEEPALIVE,true)
            ;
            ChannelFuture channelFuture = b.bind(port).sync();
            //监听关闭
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
